// ActionScript file
package Models
{
	import mx.collections.ArrayCollection;
	import mx.collections.Sort;
	import mx.collections.SortField;
	
	public class Model 
	{
		private const maxNumber : int = 1000;
		
		[Bindable]
		public var items : ArrayCollection = new ArrayCollection();
		
		[Bindable]
		public var selectedIndex : int = -1;
		
		public function Clear() : void
		{
			items = new ArrayCollection();
		}
		
		public function AddElement(date : Date) : void
		{
			if (!Contains(date))
			{
				var listItem : ListItem = new ListItem(date, Math.random() * maxNumber);
				items.addItem(listItem);
				items.refresh();
			}
		}
		
		public function SortArray() : void
		{
		 	var dataSortField:SortField = new SortField();
            dataSortField.name = "num";
            dataSortField.numeric = true;
 
            var numericDataSort:Sort = new Sort();
            numericDataSort.fields = [dataSortField];
 
            items.sort = numericDataSort;
            items.refresh();
		}
		
		public function Delete() : void
		{
			if (selectedIndex != -1)
			{
				items.removeItemAt(selectedIndex);
				selectedIndex = -1;
			}
		}
		
		private function Contains(date: Date) : Boolean
		{
			for (var i:int = 0; i < items.length; i++)
			{		
				var item:ListItem = items.getItemAt(i) as ListItem;
				if (item.date.getTime() == date.getTime())
				{
					return true;
				}
			}	
			
			return false;
		}
	} 
}